/**
 * 
 */
package com.ginger.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ginger.model.User;
import com.ginger.utils.AjaxResult;

/**
 * @Description: 认证控制层
 * @author 姜锋
 * @date 2018年6月27日 上午10:22:37 
 * @version V1.0   
 *
 */
@RestController("/auth")
public class AuthController {
	
	@PostMapping("/authentication")
	public AjaxResult AuthenticationIn(User user){
		try {
			if (user.getUserCode() == null 
					|| "".equals(user.getUserCode().trim()) 
					|| user.getPassword() == null
					|| "".equals(user.getPassword().trim())) {
				return AjaxResult.returnMessage(false, "请正确填写登录信息后重试!");
			}
			// shiro将自动调用realm
			Subject subject = SecurityUtils.getSubject();
			subject.login(new UsernamePasswordToken(user.getUserCode(), user.getPassword()));
		} catch (UnknownAccountException e) {
			return AjaxResult.returnMessage(false, "账号或密码输入错误!");
		} catch (IncorrectCredentialsException e) {
			return AjaxResult.returnMessage(false, "账号或密码输入错误!");
		} catch (LockedAccountException e) {
			return AjaxResult.returnMessage(false, "用户已被锁定,请联系管理员!");
		}catch (DisabledAccountException   e) {
			return AjaxResult.returnMessage(false, "用户已被删除");
		} 
		catch (AuthenticationException e) {
			return AjaxResult.returnMessage(false, "登录失败!");
		}
		return AjaxResult.returnStatus(true);
		
	}
	
}
